package cn.xinfei.xdecision.listener;

import cn.xinfei.xdecision.conf.XApplicationReadyEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.GenericWebApplicationContext;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

@Slf4j
@Service
public class XApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware {

    @Autowired
    private Map<String, XApplicationReadyEvent> listener;

    private static ApplicationContext context;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        Set<Map.Entry<String, XApplicationReadyEvent>> entries = listener.entrySet();
        Iterator<Map.Entry<String, XApplicationReadyEvent>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, XApplicationReadyEvent> next = iterator.next();
            String beanName = next.getKey();
            Object attribute = ((GenericWebApplicationContext) context).getBeanDefinition(beanName).getAttribute("org.springframework.context.annotation.ConfigurationClassPostProcessor.order");
            int order = (int) attribute;
            log.info("beanName={},order={}", beanName, order);
        }


    }

}
